import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';

import '../../Services/api_service.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';

import '../../model/banner_model.dart';
import '../web/web_page.dart';

class BannerWidget extends StatefulWidget {
  const BannerWidget({super.key});

  @override
  State<StatefulWidget> createState() {
    return BannerWidgetState();
  }
}

class BannerWidgetState extends State<BannerWidget> {

  List<BannerModel> _bannerList = [];

  @override
  void initState() {
    super.initState();
    _getBanner();
  }

  Future<Null> _getBanner() async {
    ApiService().getBanner((List<BannerModel> bannerList) {
      if (bannerList.isNotEmpty) {
        setState(() {
          _bannerList = bannerList;
        });
      }
    });
  }

  Widget buildItemImageWidget(BuildContext context, int index) {
    return InkWell(
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(builder: (context){
          return WebViewPage(title: _bannerList[index].title, url: _bannerList[index].url);
        }));
      },
      child: CachedNetworkImage(
        imageUrl: _bannerList[index].imagePath,
        fit: BoxFit.fill,
        placeholder: (context, url) => Container(color: Colors.grey[100]),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Swiper(
      itemBuilder: (BuildContext context, int index) {
        return buildItemImageWidget(context, index);
      },
      itemCount: _bannerList.length,
      autoplay: true,
      pagination: const SwiperPagination(),
    );
  }
}
